package Jasper.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Ran
 * @since JDK 1.8
 */
public class DBUtils {
    private static String className;
    private static String url;
    private static String username;
    private static String password;
    static{
        //给4个属性赋值
        //1.创建 Properties 对象
        Properties properties = new Properties();
        try {
            //properties.load(new FileInputStream("src/jdbc.properties"));
            properties.load(DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            className = properties.getProperty("className");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection connection = null;
        try {
            //1.加载驱动
            Class.forName(className);
            //2.通过 DriverManager 获取连接对象
            connection = DriverManager.getConnection(
                    url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
       return connection;
    }

    public static void  closeAll(AutoCloseable ... autoCloseables){
        for (AutoCloseable autoCloseable:autoCloseables) {
            if(autoCloseable != null){
                try {
                    autoCloseable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
